import request from '@/public/request'
import dayjs from 'dayjs';


let arr = [
    { type: "doc", application: "application/msword" },
    {
        type: "docx",
        application:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    },
    {
        type: "dotx",
        application:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
    },
    { type: "xls", application: "application/vnd.ms-excel" },
    {
        type: "xlsx",
        application:
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    },
    { type: "ppt", application: "application/vnd.ms-powerpoint" },
    {
        type: "pptx",
        application:
            "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    },
    { type: "pdf", application: "application/pdf" },
    { type: "txt", application: "text/plain" },
    { type: "gif", application: "image/gif" },
    { type: "jpeg", application: "image/jpeg" },
    { type: "jpg", application: "image/jpeg" },
    { type: "png", application: "image/png" },
    { type: "css", application: "text/css" },
    { type: "html", application: "text/html" },
    { type: "htm", application: "text/html" },
    { type: "xsl", application: "text/xml" },
    { type: "xml", application: "text/xml" },
    { type: "mpeg", application: "video/mpeg" },
    { type: "mpg", application: "video/mpeg" },
    { type: "avi", application: "video/x-msvideo" },
    { type: "movie", application: "video/x-sgi-movie" },
    { type: "bin", application: "application/octet-stream" },
    { type: "exe", application: "application/octet-stream" },
    { type: "so", application: "application/octet-stream" },
    { type: "dll", application: "application/octet-stream" },
    { type: "ai", application: "application/postscript" },
    { type: "dir", application: "application/x-director" },
    { type: "js", application: "application/x-javascript" },
    { type: "swf", application: "application/x-shockwave-flash" },
    { type: "xhtml", application: "application/xhtml+xml" },
    { type: "xht", application: "application/xhtml+xml" },
    { type: "zip", application: "application/zip" },
    { type: "mid", application: "audio/midi" },
    { type: "midi", application: "audio/midi" },
    { type: "mp3", application: "audio/mpeg" },
    { type: "rm", application: "audio/x-pn-realaudio" },
    { type: "rpm", application: "audio/x-pn-realaudio-plugin" },
    { type: "wav", application: "audio/x-wav" },
    { type: "bmp", application: "image/bmp" },
    // { type: "csv", application: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" },
];

export function getFIleType(application: string) {
    let val = ''
    arr.forEach(t => {
        if (t.application === application) {
            val = t.type
        }
    })
    return val
}

/** 下载文件(建议引入项目的axios，否则拦截器不生效)*/
export function fileDownload(url: string, data: { [key: string]: unknown } = {}, filenameImport: string = "") {
    return new Promise((resolve, reject) => {
        request.axios(url, {
            params: data,
            responseType: 'blob'
        })
            .then((res) => {
                if (res.data.type == "application/json") {
                    reject('文件导出失败');
                } else {
                    let downloadType = getFIleType(res.headers['content-type']);
                    const blob = new Blob([res.data]);
                    const downloadElement = document.createElement('a')
                    const href = window.URL.createObjectURL(blob)
                    let contentDisposition = res.headers['content-disposition'] //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
                    let patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
                    let result = patt.exec(contentDisposition) ? patt.exec(contentDisposition) : [];
                    let filename = result?.length ? decodeURI(result[1]) : dayjs().format("YYYY-MM-DD HH_mm_ss") + "-" + filenameImport;
                    // 只有当返回的文件blob对象需要自定义名称时使用
                    if (!result?.length) {
                        filename = filename + "." + downloadType;
                    };
                    downloadElement.style.display = 'none'
                    downloadElement.href = href
                    downloadElement.download = filename as string //下载后文件名
                    document.body.appendChild(downloadElement)
                    downloadElement.click() //点击下载
                    document.body.removeChild(downloadElement) //下载完成移除元素
                    window.URL.revokeObjectURL(href) //释放掉blob对象
                    resolve(res.data)
                };
            })
    })
}

/** 
 * 对两个数组进行合并去重
 * 前两个参数必须是数组
 * key：表示两个数据共同的唯一识别标志
*/
export function mergeAndRemoveDuplicates(arr1: object[], arr2: object[], key: string) {
    let hash: any = {};
    // 合并两个数组
    let mergedArr = arr1.concat(arr2);
    const newArr = mergedArr.reduce((item, next) => {
        hash[next[key]] ? '' : hash[next[key]] = true && item.push(next);
        return item
    }, []);
    return newArr;
}

